package com.meihuak.cloud_ordering.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpURLUtil {

    public static String HttpResult(String resultURL, Map<String,Object> params){
        StringBuilder buffer = new StringBuilder();
        try {
            URL url = new URL(resultURL+"?"+urlencode(params));
            //打开http链接
            HttpURLConnection httpURLConn = (HttpURLConnection) url.openConnection();
            httpURLConn.setDoInput(true);
            httpURLConn.setRequestMethod("POST");
            httpURLConn.connect();

            //获得输入
            InputStream is = httpURLConn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            //将bufferReader的值放到buffer里
            String str= null;
            while ((str=br.readLine())!=null){
                buffer.append(str);
            }
            //关闭bufferReader输入流
            br.close();
            isr.close();
            is.close();
            is=null;
            //断开连接
            httpURLConn.disconnect();

        }catch (Exception e){
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static String urlencode(Map<String,Object> data){
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i: data.entrySet()){
            try{
                sb.append(i.getKey()).append("=").append(i.getValue()).append("&");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return sb.toString();
    }




}
